<?php
/* 
    Name：FastPHP
    CopyRight: Mr.Fu 2019SR0832915
*/
namespace app\extend\weixin;
/*
 	微信小程序基础类 
*/
use \app\base\Common;

class Wxmin extends Common
{
  	public $AccessToken="";
  	
	public function _initialize(){
    	//执行父类的构造方法
    	parent::_initialize();
      	$APPID=$this->Config['wxauth_appid'];
      	$appsecret=$this->Config['wxauth_appsecret'];
      	$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$APPID."&secret=".$appsecret;
      	$accesstoken=Cache('wx_minapp_access_token');
      	if(is_null($accesstoken) or $accesstoken==""){
              $result=file_get_contents($url);
              $result=json_decode($result,true);
              Cache('wx_minapp_access_token',$result['access_token'],$result['expires_in']);
              $this->AccessToken=$result['access_token'];
        }else{
        	  $this->AccessToken=$accesstoken;
        }
	}
  	//生成小程序二维码
  	public function CreateCode($scene)
    {	//scene
      	$url='https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$this->AccessToken;
      	$data['scene']=$scene;
      	$d=json_encode($data);
        $result=Post_Json($d,$url);
        $DIR1="/uploads/qrcode/".MyDate('Ymd',time())."/";
		
        $FILENAME="QR_".$scene.".png";
        $path=ROOT_PATH.$DIR1;
        if(!file_exists($path)){
          	MkDirs($path);
        }
        $savefile=$path.$FILENAME;
        $return_path=$DIR1.$FILENAME;
      	file_put_contents($savefile,$result);
      	return $return_path;
    }
	//解密微信手机信息
	public function DecodeWxMobile($sessionKey,$ciphertext){
		if(!isset($ciphertext['encryptedData'])){
			return false;
		}
		$encryptedData=$ciphertext['encryptedData'];
		$iv=$ciphertext['iv'];
		$aesKey=base64_decode($sessionKey);
		$aesIV=base64_decode($iv);
		$aesCipher=base64_decode($encryptedData);
		$result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
		if(!$result){
			return false;
		}
		$result=json_decode($result,true);
		return $result;
	}
}
